package com.zt.chatgpt.trigger.http;

import com.zt.chatgpt.auth.model.entity.AuthStateEntity;
import com.zt.chatgpt.auth.model.valobj.AuthTypeVO;
import com.zt.chatgpt.auth.service.IAuthService;
import com.zt.chatgpt.types.common.Constants;
import com.zt.chatgpt.types.model.Response;
import com.zt.chatgpt.types.sdk.wexin.util.XmlUtil;
import com.zt.chatgpt.weixin.model.entity.MessageTextEntity;
import com.zt.chatgpt.weixin.model.entity.UserBehaviorMessageEntity;
import com.zt.chatgpt.weixin.model.valobj.MsgTypeVO;
import com.zt.chatgpt.weixin.service.IWeiXinBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: zt
 * @Description: 鉴权登录
 * @create: 2024-05-19 00:04
 */
@Slf4j
@RestController
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("/api/${app.config.api-version}/auth/")

public class AuthController {

    @Resource
    IAuthService authService;

    @Resource
    IWeiXinBehaviorService weiXinBehaviorService;

    /**
     * 生成验证码，用于测试使用
     * <p>
     * curl -X POST \
     *  http://zt9527.natapp1.cc/api/v1/auth/create/code \
     * -H 'Content-Type: application/x-www-form-urlencoded' \
     * -d 'openid=oxfA9w8-23yvwTmo2ombz0E4zJv4'
     *
     * curl -X POST \
     *  http://localhost:18080/api/v1/auth/create/code \
     * -H 'Content-Type: application/x-www-form-urlencoded' \
     * -d 'openid=oxfA9w8-23yvwTmo2ombz0E4zJv4'
     */
    @RequestMapping(value = "/create/code", method = RequestMethod.POST)
    public Response<String> genCode(@RequestParam String openid) {
        log.info("生成验证码开始，用户ID {}", openid);
        try {
            // 1. 生成请求对象
            UserBehaviorMessageEntity userBehaviorMessageEntity = UserBehaviorMessageEntity
                    .builder()
                    .content("101")
                    .createTime(new Date())
                    .openId(openid)
                    .msgType(MsgTypeVO.TEXT.getCode())
                    .build();
            // 2. 转化对象
            String xml = weiXinBehaviorService.acceptUserBehavior(userBehaviorMessageEntity);
            MessageTextEntity messageTextEntity = XmlUtil.xmlToBean(xml, MessageTextEntity.class);
            log.info("生成验证码结束，用户ID {} 生成结果 {} ", openid, messageTextEntity.getContent());
            // 3. 返回响应信息
            return Response.<String>builder()
                    .code(Constants.ResponseCode.SUCCESS.getCode())
                    .info(Constants.ResponseCode.SUCCESS.getInfo())
                    .data(messageTextEntity.getContent())
                    .build();
        } catch (Exception e) {
            log.error("生成验证码失败, 用户ID {}", openid);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.UN_ERROR.getCode())
                    .info(Constants.ResponseCode.UN_ERROR.getInfo())
                    .build();
        }
    }

    /**
     * 鉴权，根据鉴权结果返回 Token 码
     * curl -X POST \
     * http://zt9527.natapp1.cc/api/v1/auth/login \
     * -H 'Content-Type: application/x-www-form-urlencoded' \
     * -d 'code=0959'
     * <p>
     * curl -X POST \
     * http://zt9527.natapp1.cc/api/v1/auth/login \
     * -H 'Content-Type: application/x-www-form-urlencoded' \
     * -d 'code=8815'
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Response<String> doLogin(@RequestParam String code) {
        log.info("鉴权，登录校验开始，验证码 {}", code);
        try {
            AuthStateEntity authStateEntity = authService.doLogin(code);
            log.info("鉴权，登录校验结束，验证码 {} 结果 {}", code, authStateEntity.getCode());

            // 鉴权失败
            if (!AuthTypeVO.A0000.getCode().equals(authStateEntity.getCode())) {
                return Response.<String>builder()
                        .code(Constants.ResponseCode.TOKEN_ERROR.getCode())
                        .info(Constants.ResponseCode.TOKEN_ERROR.getInfo())
                        .build();
            }

            // 鉴权成功
            return Response.<String>builder()
                    .code(Constants.ResponseCode.SUCCESS.getCode())
                    .info(Constants.ResponseCode.SUCCESS.getInfo())
                    .data(authStateEntity.getToken())
                    .build();
        } catch (Exception e) {
            log.error("鉴权，登录校验异常，验证码 {}", code, e);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.UN_ERROR.getCode())
                    .info(Constants.ResponseCode.UN_ERROR.getInfo())
                    .build();
        }

    }
}
